﻿@using si.caha.Repository;
@using si.caha.Model;

@{
    // Set the layout page and page title
    Layout = "~/tpl/_layout.cshtml";
    PageData["PageTitle"] = "Register an Account";

    // Initialize general page variables
    var email = "";
    var password = "";
    var confirmPassword = "";
    
    // Validation
    var isValid = true;
    var errors = new Dictionary<string,string>();

    // If this is a POST request, validate and process data
    if (IsPost)
    {
        email = Request.Form["email"];
        password = Request.Form["password"];
        confirmPassword = Request.Form["confirmPassword"];
        
        // Validate the user's password and password confirmation
        if (password.IsEmpty()) 
        {
            errors.Add("Password", "The password cannot be blank.");
            isValid = false;
        }
        
        if (password != confirmPassword) 
        {
            errors.Add("ConfirmPassword", "The new password and confirmation password do not match.");
            isValid = false;
        }
        
        // If all information is valid, create a new account
        if (isValid) 
        { 
            // Insert a new user into the database
            var dataContext = new DataContext();
            var userRepository = new UserRepository(dataContext);

            // Check if user already exists
            if (!userRepository.DoesUserWithEmailExists(email)) 
            {
                // Insert email into the profile table
                var user = new User() { Email = email };
                errors = userRepository.Add(user);
            
                if (errors.Count == 0)
                {
                    // Create and associate a new entry in the membership database.
                    // If successful, continue processing the request
                    try 
                    {
                        var token = WebSecurity.CreateAccount(email, password, true);
                        
                        var portPart = "";
                        var port = Request.Url.Port;
                        if (port != 80) {
                            portPart = ":" + port;
                        }
                        var confirmationUrl = 
                        Request.Url.Scheme + 
                        "://" + Request.Url.Host + portPart + 
                        VirtualPathUtility.ToAbsolute("~/Account/Confirm?confirmationCode=" + Server.UrlEncode(token));
                        
                        WebMail.Send(
                            to: email,	
                            subject: "Please confirm your account", 
                            body: "Your confirmation code is: " + token + 
                            ". Visit <a href=\"" + confirmationUrl + "\">" + confirmationUrl + "</a> to activate your account."
                        );
                            
                        // Thank the user for registering and let them know an email is on its way
                        Response.Redirect("~/Account/Thanks");
                    } 
                    catch (System.Web.Security.MembershipCreateUserException e) 
                    {
                        isValid = false;
                        errors.Add("AccountCreation", e.ToString());
                    }
                }
            } 
            else 
            {
                // User already exists
                isValid = false;
                errors.Add("AccountCreation", "Email address is already in use.");
            }
        }
    }
}

<p>
   Use the form below to create a new account. 
</p>

@* If at least one validation error exists, notify the user *@
@if (!isValid) 
{
   <div>
    @if (!errors.ContainsKey("AccountCreation"))
    {
        @:Please correct the errors and try again.
    }
    else 
    {
        @errors["AccountCreation"]
    }
   </div>
}

<fieldset>
    <legend>Sign-up Form</legend>
    <form method="post" action="">
        <div>
            <label for="email" id="labelEmail">Email:</label>
            <input type="email" id="email" name="email" value="@email" />
            @if (errors.ContainsKey("Email"))
            {
                <span>@errors["Email"]</span>
            }
        </div>                       
        <div>
            <label for="password" id="labelPassword">Password:</label>
            <input type="password" id="password" name="password" value="" />
            @if (errors.ContainsKey("Password"))
            {
                <span>@errors["Password"]</span>
            }
        </div>                       
        <div>
            <label for="confirmPassword" id="labelConfirmPassword">Confirm Password:</label>
            <input type="password" id="confirmPassword" name="confirmPassword" value="" />
            @if (errors.ContainsKey("ConfirmPassword"))
            {
                <span>@errors["ConfirmPassword"]</span>
            }
        </div>
        <div>
            <input type="submit" value="Register" />
        </div>
   </form>
</fieldset>
